package cn.aishua.ui.myKaka;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.aishua.R;
import cn.aishua.network.HttpRequestUtil;
import cn.aishua.ui.MainActivityGroup;
import cn.aishua.ui.myKaka.task.DataExchangeAsyncTask;
import cn.aishua.ui.setting.SettingActivity;
import cn.aishua.util.FormatConverter;

public class MemberCenterActivity
    extends Activity
{
    public static final String EXTRA_MSG_REAL_NAME = "cn.aishua.ui.myKaka.realName";
    public static final String EXTRA_MSG_GENDER = "cn.aishua.ui.myKaka.gender";
    public static final String EXTRA_MSG_BIRTH_DATE = "cn.aishua.ui.myKaka.birthDate";
    //    public static final String EXTRA_MSG_RESIDENCE = "cn.aishua.ui.myKaka.residence";
    public static final String EXTRA_MSG_PROVINCE = "cn.aishua.ui.myKaka.province";
    public static final String EXTRA_MSG_CITY = "cn.aishua.ui.myKaka.city";
    public static final String EXTRA_MSG_DISTRICT = "cn.aishua.ui.myKaka.district";
    public static final String EXTRA_MSG_ADDRESS = "cn.aishua.ui.myKaka.address";

    public static final String SHARED_PREF_STR_MOBILE_NUMBER = "STR_MOBILE_NUMBER";
    public static final String SHARED_PREF_STR_ACCOUNT_NAME = "STR_ACCOUNT_NAME";
    public static final String SHARED_PREF_STR_USER_CREDIT = "STR_USER_CREDIT";

    public static String JSON_RES; // if auto login is checked, json response will be retrieved at first place

    private TextView tvUserName;
    private TextView tvRealName;
    private TextView tvGender;
    private TextView tvBirthDate;
    private TextView tvResidence;
    private TextView tvCredits;

    private String strProvince;
    private String strCity;
    private String strCounty;
    private String strAddress;

    // page header widgets
    private ImageView ivLeftBtn;
    private ImageView ivRightBtn;
    private TextView tvTitile;

    private void initPageHeader()
    {
        // left button
        ivLeftBtn = (ImageView) findViewById( R.id.page_header_iv_left_btn );
        ivLeftBtn.setImageResource( R.drawable.btn_nav_header );
        ivLeftBtn.setOnClickListener( new View.OnClickListener()
        {

            @Override
            public void onClick( View v )
            {
                navigationBar();
            }
        } );

        // title
        tvTitile = (TextView) findViewById( R.id.page_header_tv_title );
        tvTitile.setText( "会员中心" );

        // right button
        ivRightBtn = (ImageView) findViewById( R.id.page_header_iv_right_btn );
        ivRightBtn.setVisibility( View.GONE );
    }

    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        Log.d( "MemberCenterActivity", "onCreate()" );
        super.onCreate( savedInstanceState );
        setContentView( R.layout.my_kaka_member_center );
        initPageHeader();
        initiate();
        retrieveData();
    }
    
    @Override
    protected void onResume()
    {
        Log.d( "MemberCenterActivity", "onResume()" );
        super.onResume();
    }

//    @Override
//    protected void onNewIntent( Intent intent )
//    {
//        Log.d( "MemberCenterActivity", "onNewIntent()" );
//        super.onNewIntent( intent );
//        retrieveData();
//    }
//    
    private void retrieveData()
    {

        if( JSON_RES != null ) // retrieved at first place
        {
            try
            {
                analyseJsonRes( JSON_RES );
            }
            catch( JSONException e )
            {
                Log.d( "MemeberCenterActivity", e.getMessage() );
            }
            JSON_RES = null;
        }
        else
        {

            new DataExchangeAsyncTask( this, "获取用户信息" )
            {

                @Override
                protected HttpResponse sendRequest( String... params )
                {
                    return HttpRequestUtil.getInstance().getUserinfo();
                }

                @Override
                protected void handleSuccResponse( String strJson ) throws Exception
                {

                    analyseJsonRes( strJson );
                }

            }.execute();
        }
    }

    private void initiate()
    {
        tvUserName = (TextView) findViewById( R.id.my_kaka_member_center_tv_user_name );
        tvCredits = (TextView) findViewById( R.id.my_kaka_member_center_tv_credits );
        tvRealName = (TextView) findViewById( R.id.my_kaka_member_center_tv_real_name );
        tvGender = (TextView) findViewById( R.id.my_kaka_member_center_tv_gender );
        tvBirthDate = (TextView) findViewById( R.id.my_kaka_member_center_tv_birth_date );
        tvResidence = (TextView) findViewById( R.id.my_kaka_member_center_tv_residence );
    }

    public void navigationBar()
    {
        MainActivityGroup parent = (MainActivityGroup) getParent();
        parent.handleNaviBar();
    }

    public void toUserInfoPage( View view )
    {
        Intent intent = new Intent( this, UserInfoActivity.class );
        intent.putExtra( EXTRA_MSG_REAL_NAME, tvRealName.getText() );
        intent.putExtra( EXTRA_MSG_GENDER, tvGender.getText() );
        intent.putExtra( EXTRA_MSG_BIRTH_DATE, tvBirthDate.getText() );

        intent.putExtra( EXTRA_MSG_PROVINCE, strProvince );
        intent.putExtra( EXTRA_MSG_CITY, strCity );
        intent.putExtra( EXTRA_MSG_DISTRICT, strCounty );
        intent.putExtra( EXTRA_MSG_ADDRESS, strAddress );

        startActivity( intent );

    }

    private void analyseJsonRes( String strJson ) throws JSONException
    {
        String mobileNumber = null;

        JSONObject jsonResult = new JSONObject( strJson );
        JSONObject jsonObj = jsonResult.getJSONObject( "user" );
        String userName = jsonObj.getString( "account_name" );
        tvUserName.setText( userName );
        int credit = jsonObj.getInt( "usable_credit" );
        tvCredits.setText( "" + credit );

        String emptyValue = "未填写";
        tvRealName.setText( FormatConverter.getJsonString( jsonObj, "real_name", emptyValue ) );
        tvGender.setText( FormatConverter.getJsonString( jsonObj, "gender", emptyValue ) );
        tvBirthDate.setText( FormatConverter.getJsonString( jsonObj, "birthday", emptyValue ) );
        mobileNumber = jsonObj.getString( "mobile" );

        strProvince = FormatConverter.getJsonString( jsonObj, "province", "" );
        strCity = FormatConverter.getJsonString( jsonObj, "city", "" );
        strCounty = FormatConverter.getJsonString( jsonObj, "county", "" );
        strAddress = FormatConverter.getJsonString( jsonObj, "address", "" );

        StringBuffer displayAddress = new StringBuffer();
        displayAddress.append( strProvince );
        displayAddress.append( strCity );
        displayAddress.append( strCounty );
        String addr = displayAddress.toString().trim();

        tvResidence.setText( addr.equals( "" ) ? emptyValue : addr );

        tvUserName.setText( userName );
        tvCredits.setText( "" + credit );

        // store the mobile number to furthur use
        SharedPreferences sharedPref = getSharedPreferences( "userInfo", Context.MODE_PRIVATE );
        Editor editor = sharedPref.edit();
        editor.putString( SHARED_PREF_STR_MOBILE_NUMBER, mobileNumber );
        editor.putString( SHARED_PREF_STR_ACCOUNT_NAME, userName );
        editor.putString( SHARED_PREF_STR_USER_CREDIT, "" + credit );
        editor.commit();

        MainActivityGroup parent = (MainActivityGroup) getParent();
        parent.updateUserInfo();
    }

    public void toMyBankCardPage( View view )
    {
        Intent toMyBankCardPage = new Intent( this, MyBankCardActivity.class );
        startActivity( toMyBankCardPage );
    }

    public void toSettingPage( View view )
    {
        Intent intent = new Intent( this, SettingActivity.class );
        startActivity( intent );

    }

    public void toCreditExchangePage( View view )
    {
        Intent toCreditExchangePage = new Intent( this, CreditExchangeActivity.class );

        startActivity( toCreditExchangePage );
    }

    public void toMyFavoritePage( View view )
    {
        Intent toMyFavoritePage = new Intent( this, MyFavoriteActivity.class );
        startActivity( toMyFavoritePage );
    }

    public void toMyCreditPage( View view )
    {

        Intent toMyCreditPage = new Intent( this, MyCreditActivity.class );
        startActivity( toMyCreditPage );

    }

    public void logout( View view )
    {
        new AsyncTask<String, Void, HttpResponse>()
        {

            ProgressDialog dialog;

            @Override
            protected void onPreExecute()
            {
                dialog = ProgressDialog.show( MemberCenterActivity.this.getParent(), "注销", "正在连接服务器", false );
            }

            @Override
            protected HttpResponse doInBackground( String... params )
            {

                HttpResponse res = HttpRequestUtil.getInstance().logout();
                return res;
            }

            @Override
            protected void onPostExecute( HttpResponse result )
            {
                dialog.dismiss();

                if( HttpStatus.SC_OK == result.getStatusLine().getStatusCode() )
                {
                    Toast.makeText( MemberCenterActivity.this.getParent(), "注销成功", Toast.LENGTH_LONG ).show();
                    Intent backToLoginPage = new Intent( getApplicationContext(), LoginActivity.class );
                    backToLoginPage.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );

                    View loginPage = MyKakaActivityGroup.group.getLocalActivityManager()
                        .startActivity( MyKakaActivityGroup.ID_LOGIN, backToLoginPage ).getDecorView();
                    MyKakaActivityGroup.group.setContentView( loginPage );
                }
                else
                {
                    Toast.makeText( MemberCenterActivity.this.getParent(), "连接失败", Toast.LENGTH_LONG ).show();
                }
            }

        }.execute( "" );
    }

}
